package edu.cmu.cs.webapp.ioms.ui.wizards.order;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.ClientDAOImpl;
import edu.cmu.cs.webapp.ioms.models.Client;
import edu.cmu.cs.webapp.ioms.models.PurchaseOrder;
import edu.cmu.cs.webapp.ioms.models.impl.IOMSFactoryImpl;
import edu.cmu.cs.webapp.ioms.ui.dialogs.product.BrowseCustomersDialog;
import edu.cmu.cs.webapp.ioms.utils.SWTUtils;
import edu.cmu.cs.webapp.ioms.views.CustomersListView;

/**
 * 
 * @author Christian
 */
public class OrderCustomerWizardPage extends WizardPage {

	private Text custIDTxt;
	private Text lnameTxt;
	private Text fnameTxt;
	private Text emailTxt;
	private Text phoneTxt;
	private Text companyTxt;
	private Text addressTxt;
	private Text cityTxt;
	private Combo stateComb;
	private Text countryTxt;
	private Button _browseBtn;
	private Button _createNewBtn;

	private Client client;

	private Composite _newCustomerComp;

	public OrderCustomerWizardPage(String pageName) {
		super(pageName);
		setTitle("Order Main");
		setDescription("Input the general infomation of the new order. \nNotice: All fields with asterisk(*) are required");

	}

	public OrderCustomerWizardPage(String pageName, String title,
			ImageDescriptor titleImage) {
		super(pageName, title, titleImage);
	}

	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);

		layout.numColumns = 3;
		// layout.verticalSpacing = 9;

		Label label = new Label(container, SWT.NULL);

		/* id */
		label.setText("Customer*:"); //$NON-NLS-1$

		custIDTxt = new Text(container, SWT.BORDER | SWT.SINGLE);

		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		// _memberIDTxt.setEditable(false);
		custIDTxt.setLayoutData(gd);
		custIDTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		this.custIDTxt.setEditable(false);
		this.custIDTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		_browseBtn = new Button(container, SWT.FLAT);
		_browseBtn.setText("Browse...");
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 1;
		gd.grabExcessHorizontalSpace = false;
		_browseBtn.setLayoutData(gd);
		_browseBtn.addSelectionListener(new SelectionListener() {

			public void widgetDefaultSelected(SelectionEvent e) {
			}

			public void widgetSelected(SelectionEvent e) {
				BrowseCustomersDialog dlg = new BrowseCustomersDialog(
						getShell());
				if (dlg.open() == IDialogConstants.OK_ID) {
					client = dlg.getSelectedModel();
					custIDTxt.setText(client.getFname() + " "
							+ client.getLname() + "(#" + client.getClient_id()
							+ ")");
				}
			}
		});

		createLine(container, layout.numColumns);

		_createNewBtn = SWTUtils.createCheckBox(container, "Create customer",
				3, 10);
		this._createNewBtn.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				setCreateNewGroupEnabled(_createNewBtn.getSelection());
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {

			}
		});

		_newCustomerComp = new Composite(container, SWT.NONE);
		layout = new GridLayout();
		layout.numColumns = 3;
		_newCustomerComp.setLayout(layout);
		GridData gds = new GridData(SWT.FILL, SWT.FILL, true, true);
		gds.horizontalSpan = 3;
		_newCustomerComp.setLayoutData(gds);

		// first name
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("First Name*:"); //$NON-NLS-1$
		fnameTxt = new Text(_newCustomerComp, SWT.BORDER);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		fnameTxt.setLayoutData(gd);
		fnameTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		// last name
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("Last Name*:"); //$NON-NLS-1$
		lnameTxt = new Text(_newCustomerComp, SWT.BORDER);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		lnameTxt.setLayoutData(gd);
		lnameTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});
		
		// email
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("Email:"); //$NON-NLS-1$
		emailTxt = new Text(_newCustomerComp, SWT.BORDER);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		emailTxt.setLayoutData(gd);
		emailTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});
		
		// phone
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("Phone*:"); //$NON-NLS-1$

		phoneTxt = new Text(_newCustomerComp, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		phoneTxt.setLayoutData(gd);
		phoneTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		// company
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("Company:"); //$NON-NLS-1$

		companyTxt = new Text(_newCustomerComp, SWT.BORDER);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		companyTxt.setLayoutData(gd);
		gd.horizontalSpan = 2;
		companyTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		// address
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("Address:"); //$NON-NLS-1$

		addressTxt = new Text(_newCustomerComp, SWT.BORDER);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		addressTxt.setLayoutData(gd);
		addressTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		// city
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("City:"); //$NON-NLS-1$

		cityTxt = new Text(_newCustomerComp, SWT.BORDER);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		cityTxt.setLayoutData(gd);
		cityTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		// state
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("State:"); //$NON-NLS-1$

		stateComb = new Combo(_newCustomerComp, SWT.BORDER);
		stateComb.select(0);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		stateComb.setLayoutData(gd);
		stateComb.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		// country
		label = new Label(_newCustomerComp, SWT.NULL);
		label.setText("Country:"); //$NON-NLS-1$

		countryTxt = new Text(_newCustomerComp, SWT.BORDER);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		countryTxt.setLayoutData(gd);
		countryTxt.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validate();
			}
		});

		setCreateNewGroupEnabled(false);

		if (isUpdate()) {
			loadFromExistingModel();
		}

		setControl(container);
		validate();
		container.pack(true);

	}

	private void loadFromExistingModel() {
		PurchaseOrder model = getModel();
		if (model != null) {
			client = model.getClient();
			if (client != null) {
				custIDTxt.setText(client.getFname() + " " + client.getLname()
						+ "(#" + client.getClient_id() + ")");
			}
		}
	}

	private void setCreateNewGroupEnabled(boolean enable) {
		this._newCustomerComp.setVisible(enable);
	}

	private void createLine(Composite parent, int ncol) {
		Label line = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL
				| SWT.BOLD);
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = ncol;
		line.setLayoutData(gridData);
	}

	private boolean validate() {
		boolean valid = true;
		String errorMessage = null;

		if (isCreateNew()) {
			if (valid && (getFname() == null || getFname().length() == 0)) {
				valid = false;
				errorMessage = "First name field could not be empty";
			}

			if (valid && (getLname() == null || getLname().length() == 0)) {
				valid = false;
				errorMessage = "Last name field could not be empty";
			}

			if (valid && (getPhone() == null || getPhone().length() == 0)) {
				valid = false;
				errorMessage = "Phone field could not be empty";
			}
		} else {
			if (valid && (client == null)) {
				valid = false;
				errorMessage = "Customer must be assigned for this order";
			}
		}

		if (valid) {
			setErrorMessage(null);
			setPageComplete(true);
		} else {
			setErrorMessage(errorMessage);
			setPageComplete(false);
		}

		return valid;

	}

	public String getCustID() {
		return custIDTxt.getText();
	}

	public String getLname() {
		return lnameTxt.getText();
	}

	public String getFname() {
		return fnameTxt.getText();
	}

	public String getEmail() {
		return emailTxt.getText();
	}

	public String getPhone() {
		return phoneTxt.getText();
	}

	public String getCompany() {
		return companyTxt.getText();
	}

	public String getAddress() {
		return addressTxt.getText();
	}

	public String getCity() {
		return cityTxt.getText();
	}

	public String getState() {
		return this.stateComb.getText();
	}

	public String getCountry() {
		return countryTxt.getText();
	}

	private boolean isUpdate() {
		return ((OrderWizard) getWizard()).isUpdate();
	}

	private PurchaseOrder getModel() {
		return ((OrderWizard) getWizard()).getModel();
	}

	public boolean isCreateNew() {
		return _createNewBtn.getSelection();
	}

	public Client getClient() {
		if (isCreateNew()) {
			client = IOMSFactoryImpl.eINSTANCE.createClient();
			// client.setClient_id(_clientPage.getCustID());
			client.setFname(getFname());
			client.setLname(getLname());
			client.setAddress(getAddress());
			client.setPhone(getPhone());
			client.setEmail(getEmail());
			client.setCity(getCity());
			client.setState(getState());
			client.setCountry(getCountry());
			try {
				client.setClient_id(new ClientDAOImpl().addClient(client));
			} catch (DataAccessException e) {
			}
		}

		return client;
	}

}
